<template>
	<view class="verify-container">
		<uv-toast ref="toast"></uv-toast>

		<!-- 顶部标题区域 -->
		<view class="header">
			<text class="title">早餐券核销</text>
			<text class="subtitle">请选择核销方式</text>
		</view>

		<!-- 核销方式选择区域 -->
		<view class="verify-methods">
			<!-- 扫码核销 -->
			<view class="method-card" :class="{ active: verifyMethod === 'scan' }" @tap="switchMethod('scan')">
				<view class="method-icon">
					<uv-icon name="scan" size="80" color="#ff9800"></uv-icon>
				</view>
				<view class="method-info">
					<text class="method-title">扫码核销</text>
					<text class="method-desc">扫描用户出示的券码二维码</text>
				</view>
				<view class="check-icon" v-if="verifyMethod === 'scan'">
					<uv-icon name="checkmark" size="44" color="#ff9800"></uv-icon>
				</view>
			</view>

			<!-- 手动核销 -->
			<view class="method-card" :class="{ active: verifyMethod === 'manual' }" @tap="switchMethod('manual')">
				<view class="method-icon">
					<uv-icon name="edit-pen" size="80" color="#ff9800"></uv-icon>
				</view>
				<view class="method-info">
					<text class="method-title">手动核销</text>
					<text class="method-desc">手动输入券码进行核销</text>
				</view>
				<view class="check-icon" v-if="verifyMethod === 'manual'">
					<uv-icon name="checkmark" size="44" color="#ff9800"></uv-icon>
				</view>
			</view>
		</view>

		<!-- 扫码区域 -->
		<view class="scan-area" v-if="verifyMethod === 'scan'">
			<view class="scan-box">
				<camera class="camera" mode="scanCode" @scancode="onScanCode"></camera>
				<view class="scan-line"></view>
			</view>
			<text class="scan-tip">请将二维码放入框内</text>
		</view>

		<!-- 手动输入区域 -->
		<view class="manual-area" v-if="verifyMethod === 'manual'">
			<view class="input-box">
				<input type="text" v-model="couponCode" placeholder="请输入券码" placeholder-class="placeholder"
					maxlength="12" />
			</view>
			<button class="verify-btn" :disabled="!couponCode" @tap="verifyCoupon">
				确认核销
			</button>
		</view>

		<!-- 最近核销记录 -->
		<view class="recent-records" v-if="recentRecords.length > 0">
			<view class="records-title">
				<text>最近核销记录</text>
			</view>
			<view class="record-list">
				<view class="record-item" v-for="(record, index) in recentRecords" :key="index">
					<view class="record-info">
						<text class="record-code">券码：{{ record.couponCode }}</text>
						<text class="record-time">{{ record.createAt }}</text>
					</view>
					<text class="record-status">已核销</text>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				merchantId: 0,
				verifyMethod: 'scan', // scan 或 manual
				couponCode: '',
				loading: false, // 加载状态
				finished: false, // 是否加载完成
				recentRecords: [], // 最近核销记录
				typeValue: 0,
				pageNum: 1,
				pageSize: 5
			}
		},

		methods: {
			// 切换核销方式
			switchMethod(method) {
				this.verifyMethod = method;
				this.couponCode = '';
				if (this.verifyMethod === 'scan') {
					// 扫码核验
					this.typeValue = 0;
					this.requestCameraPermission();
				} else {
					this.typeValue = 1;
				}
				this.resetPagination();
				this.fetchRecord();
			},
			
			// 请求相机权限
			requestCameraPermission() {
				uni.authorize({
					scope: 'scope.camera',
					success() {
						console.log('相机权限获取成功');
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '需要相机权限才能扫码，请在设置中开启',
							showCancel: false,
							success: () => {
								uni.openSetting();
							}
						});
					}
				});
			},

			// 扫码回调
			async onScanCode(e) {
				let code = e.detail.result;
				code = code.substring(code.lastIndexOf('=') + 1);
				await this.verifyCouponByCode(code);
			},
			async fetchRecord() {
				try {
					if (this.loading || this.finished) return;

					this.loading = true;
					const data = await this.$http.get(
						`/coupon/verify/record/list?merchantId=${this.merchantId}&pageNum=${this.pageNum}&pageSize=${this.pageSize}&status=${1}`
					);

					// 处理返回的数据
					if (data && data.items) {
						// 格式化时间并添加到列表
						const formattedRecords = data.items.map(record => ({
							...record,
							time: this.formatDateTime(record.createTime) // 假设后端返回的时间字段是 createTime
						}));

						if (this.pageNum === 1) {
							this.recentRecords = formattedRecords;
						} else {
							this.recentRecords = [...this.recentRecords, ...formattedRecords];
						}

						// 判断是否还有更多数据
						if (this.recentRecords.length >= data.count) {
							this.finished = true;
						} else {
							this.pageNum++;
						}
					}
				} catch (e) {
					this.showToast('加载记录失败', 'error');
					console.error('加载记录失败:', e);
				} finally {
					this.loading = false;
				}
			},
			// 格式化日期时间
			formatDateTime(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hour}:${minute}`;
			},

			// 重置分页数据
			resetPagination() {
				this.pageNum = 1;
				this.finished = false;
				this.recentRecords = [];
			},

			// 手动核销
			async verifyCoupon() {
				if (!this.couponCode) {
					this.showToast('请输入券码');
					return;
				}
				this.verifyCouponByCode(this.couponCode);
			},

			// 核销处理
			verifyCouponByCode(code) {
				// 跳转到核验页面
				uni.redirectTo({
					url: `/subpkg/verify_result/verify_result?code=${code}&type=${this.typeValue}`,
				})
			},

			// 显示提示
			showToast(msg, type = 'default') {
				this.$refs.toast.show({
					message: msg,
					type: type
				});
			}
		},

		onLoad(options) {
			this.merchantId = options.merchantId;
			this.fetchRecord();
		},

		onReachBottom() {
			this.fetchRecord();
		}
	}
</script>

<style lang="scss" scoped>
	@import 'verify_breakfast_coupon.scss';
</style>